package com.seal.yoyoshop.adminweb;

import com.seal.yoyoshop.bin.User;
import com.seal.yoyoshop.service.UserService;
import com.seal.yoyoshop.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UserAddServlet", value = "/admin/userAdd")
public class UserAddServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",2);

        request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("flag",2);
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        if(username.length() > 30){
            request.setAttribute("msg","添加失败，用户名过长");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        if(name.length() > 20){
            request.setAttribute("msg","添加失败，姓名过长");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
        String phone = request.getParameter("phone");
        try {
            long phoneLong = Long.parseLong(phone);
        }catch (Exception e) {
            request.setAttribute("msg","添加失败，手机号错误");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
        String address = request.getParameter("address");
        if(address.length() > 100){
            request.setAttribute("msg","添加失败，家庭住址过长");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
//        判断用户名是否重复
        User findUser = userService.getUserByUsername(username);
        if(findUser!= null){
            request.setAttribute("msg","添加失败，用户名重复");
            request.getRequestDispatcher("/admin/user_add.jsp").forward(request, response);
            return;
        }
//        新建用户
        User user = new User(null, username, password, name, phone, address, 1);
        int isSuccess = userService.newUser(user);

        response.sendRedirect("userList?page=1&size=16");


    }
}
